package com.xnxy.design.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xnxy.design.model.User;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		System.out.println("LoginFilter.destroy()");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		// 将请求和相应强制转换成servlet中的请求和相应
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		// 获取session对象，并且查看session中是否还有user对象
		HttpSession session = req.getSession();
		User user = (User) session.getAttribute("user");
		String path = req.getRequestURI();
		// 判断对象是否为空
		if (user != null || path.indexOf("login") != -1
				|| path.indexOf(".css") != -1
				|| path.indexOf(".js") != -1
				|| path.indexOf(".jpg") != -1
				|| path.indexOf(".jpeg") != -1
				|| path.indexOf(".png") != -1
				|| path.indexOf(".html") != -1
				|| path.indexOf("isLogin") != -1
				|| path.indexOf("user/inster") != -1
				|| path.indexOf("zhuce") != -1
				|| path.indexOf("admin") != -1
				|| path.indexOf("announcement") != -1
				|| path.indexOf("news") != -1
				|| path.indexOf("index") != -1) {
			if ((req.getRequestURI().contains("login")||req.getRequestURI().contains("zhuce"))&&user!=null) {
				if (!"/admin/login.html".equals(path)){
					resp.sendRedirect("/index");
				}else {
					chain.doFilter(request, response);
				}
				return;
			}
				chain.doFilter(request, response);
		} else {
			resp.sendRedirect("/login");
			return;
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("LoginFilter.init()");
	}

}
